$(document).ready(function() {
	var content = "";
	content = createFirstLever(result);
	$("#deptDiv").append(content);
})

function createFirstLever(result) {
	if (!result) {
		return;
	}
	var content = $("<ul class=\"tree-sublist\"></ul>");
	var _list = document.createDocumentFragment();
	_list = $(_list);
	$.each(result, function(index) {
		var _this = this, _h4 = $("<h4 class=\"tree-item-name\"> <span class=\"name-text\"><a href='javascript:void(0);' class='detail' title='详情'>" + _this.depName + "</a><a href='javascript:void(0);' class='add-child'>新建下级部门</a></span></h4>"), _item = $("<li class=\"tree-subitem  tree-subitem-last\"></li>"), _itemChildren, _icon;
		_h4.data("data", _this);
		_h4.find(".detail").click(function(evt) {
			var depCode = _h4.data('data').depCode;
			var flag = "dep";
			showDeptDetail(depCode, flag);
		});
		_h4.find(".add-child").click(function(evt) {
			evt.stopPropagation();
			var flag = "xjDep"
			var depCode = _h4.data('data').depCode;
			showDeptDetail(depCode, flag);
		});
		_item.append(_h4);
		if (_this.children && _this.children.length > 0) {
			_icon = $("<span class=\"tree-icon tree-children tree-children-active\"></span>");
			_h4.find(".name-text").prepend(_icon);
			_itemChildren = createFirstLever(_this.children)
			if (_itemChildren) {
				_item.append(_itemChildren);
			}
		}

		if (_icon) {
			_icon.click(function(evt) {
				evt.stopPropagation();
				var _thar = $(this).parent().parent();
				var __h4 = _thar.next();
				if (__h4.css("display") == "block") {
					__h4.css({
						"display" : "none"
					});
					$(this).removeClass("tree-children-active");
				} else {
					__h4.css({
						"display" : "block"
					});
					$(this).addClass("tree-children-active");
				}
			});
		}
		_list.append(_item);
	});

	content.append(_list);
	return content;
}

// 展现部门的详细信息
function showDeptDetail(depId, flag) {
	$.ajax({
		url : '/IMS/depart/getDeptByDepId.ht',
		data : {
			depId : depId
		},
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data) {
			var code = data.code;
			var isCharge = data.isCharge;
			$("#pcCode").val(data.result.pcid);
			if (code == '0') {// 成功
				var dataResult = data.result;
				clearAdd();
				clearUpdate();
				if (flag == "dep") {
					createJobDoc(dataResult, depId, isCharge);
				} else {
					createJobDocNew(dataResult, depId, isCharge);
				}
			} else {
				_alert("该部门下没有职位信息,如需请添加");
			}
			hideProccessBar();
		}
	});
}

function createJobDocNew(jobReult, depCode, isCharge) {
	$("#updateJobUl").hide();
	$("#addJobUl").show();
	if (jobReult.depName != null && jobReult.depName != "") {
		$("#xjDepNameInput").val(jobReult.depName);
		$("#xjDepCode").val(depCode);
	}
	$("#companyCode").val(pcid);
	$("#communityCode").val(cid);
	$("#pcidName").val(companyName);
	$("#cidName").val(communityName);
}

function createJobDoc(jobReult, depCode, isCharge) {
	$("#addJobUl").hide();
	$("#updateJobUl").show();
	if (jobReult.superDepName != null && jobReult.superDepName != "") {
		$("#updatePreDepName").append("<span>" + jobReult.superDepName + "</span>");
	} else {
		if ($("ht_communityId").val() == null || $("ht_communityId").val() == "" || $("ht_communityId").val() == "undefined") {
			$("#updatePreDepName").append("<span>" + companyName + "</span>");
		} else {
			$("#updatePreDepName").append("<span>" + communityName + "</span>");
		}
	}
	$("#udateDepNameInput").val(jobReult.depName);
	$("#updateDepCodeInput").val(depCode);

	$("#updateleaderNameInput").val(jobReult.director);
	var content = "";
	if (jobReult.positions) {
		var jobs = jobReult.positions;
		$.each(jobs, function(index) {
			content = content + "<div class='row-item-right'>";
			content = content + "<input style=\"width:132px;\" maxlength=\"50\" type=\"text\" id=\"posName\" name =\"posName\" class=\"input\" value=\"" + jobs[index].posName + "\"/><input type=\"hidden\" name =\"posCode\"  value=\"" + jobs[index].posCode + "\"/>";
			var posCode = jobs[index].isChargePos;
			var optionDom = buildzg(posCode, isCharge);
			content = content + " 主管岗： <select style='width: 55px;' name ='isChargePos' id=\'isChargePos" + index + "\'>"
			content = content + optionDom;
			content = content + "</select>";
			content = content + " <a class=\"del-child\" onclick=\'delPostion(\"" + jobs[index].posCode + "\")\'>删除</a> "
			content = content + "</div>";
		});
		$("#updateJob").append(content);
	}
}
function buildzg(posCode, dictZg) {
	var optionDom = ""
	$.each(dictZg, function(index) {
		if (posCode == dictZg[index].dictValue) {
			optionDom += "<option selected='selected' value='" + dictZg[index].dictValue + "' " + ">" + dictZg[index].dictDestination + "</option>";
		} else {
			optionDom += "<option value='" + dictZg[index].dictValue + "' " + ">" + dictZg[index].dictDestination + "</option>";
		}
	});
	return optionDom;
}

function delPostion(posCode) {
	var depCode = $("#updateDepCodeInput").val();
	var flag = "dep";
	var url = '/IMS/depart/delPostion.ht';
	_confirm("<span style='color:#FE6600'>确认删除该职位吗？</span>", function() {
		$.ajax({
			type : 'post',
			async : false,
			url : url,
			data : {
				posCode : posCode
			},
			dataType : 'json',
			beforeSend : function() {
				showProccessBar();
			},
			error : function() {
				hideProccessBar();
			},
			success : function(value) {
				var code = value.code;
				if (code == 0) {
					_alert("删除成功", function() {
						showDeptDetail(depCode, flag)
					});
				} else {
					var message = value.msg;
					_alert(message);
					return;
				}
				hideProccessBar();
			}
		});
	});
}

function clearAdd() {
	$("#xjDepNameInput").empty();
	$("#depName").val("");
	$("#updateleaderNameInput").val("");
	$("#updateJob").empty();
	$("#companyCode").empty();
	$("#communityCode").empty();
	$("#pcidName").empty();
	$("#cidName").empty();
	$("#addPosName").val("");
	$("#addPosName1").val("");
	$("#addPosCharge").val("0");
	var chargeName = $("div[name='posDepA']");
	$.each(chargeName, function(index) {
		cName = $("#" + $(chargeName[index]).attr("id"));
		$(cName).remove();
	});
	$("#posCode").val();
}

function clearUpdate() {
	$("#updatePreDepName").empty();
	$("#udateDepNameInput").val("");
	$("#updateleaderNameInput").val("");
	$("#updateJob").empty();
	$("#posCode").empty();
	var chargeName = $("div[name='posDep']");
	$.each(chargeName, function(index) {
		cName = $("#" + $(chargeName[index]).attr("id"));
		$(cName).remove();
	});
	$("#posCode").val();
}

function delDep() {
	var pcid = $("#ht_companyId").val();
	var cid = $("#ht_communityId").val();
	var depCode = $("#updateDepCodeInput").val();
	var url = '/IMS/depart/delDepartment.ht';
	if (depCode == null || depCode == "") {
		_alert("请选择要删除的部门")
	} else {
		_confirm("<span style='color:#FE6600'>删除部门后，原部门员工将自动归入未分配的部门中，是否继续删除该部门？</span>", function() {
			$.ajax({
				type : 'post',
				async : false,
				url : url,
				data : {
					depCode : depCode
				},
				dataType : 'json',
				beforeSend : function() {
					showProccessBar();
				},
				error : function() {
					hideProccessBar();
				},
				success : function(value) {
					var code = value.code;
					if (code == 0) {
						var listUrl = '/IMS/depart/showList.ht';
						listUrl = listUrl + "?companyId=" + pcid + "&cid=" + cid;
						_alert("删除成功", function() {
							$.go(listUrl, {
								dataType : 'html',
								error : function() {
									hideProccessBar();
								},
								success : function(data, textStatus) {
									replaceDocument(listUrl, data);
								}
							});
						});
					} else {
						var message = value.msg;
						_alert(message);
						hideProccessBar();
						return;
					}
				}
			});
		});
	}
}

// 添加职位
function addJob(pcid, cid, companyName, communityName) {
	var communityNameT = $("#select2-communityId-container").text()
	$("#updateJobUl").hide();
	depList();
	$("#companyCode").val(pcid);
	$("#communityCode").val(cid);
	$("#pcidName").val(companyName);
	$("#cidName").val(communityNameT);
	if (communityNameT == null || communityNameT == '' || communityNameT == '请选择小区' || communityNameT == '查看全部') {
		$("#xjDepNameInput").val(companyName);
		$("#cidName").val("");
	} else {
		$("#xjDepNameInput").val(communityNameT);
	}
	$("#addJobUl").show();
}

function saveDepAndPos() {
	var pcid = $("#ht_companyId").val();
	var cid = $("#ht_communityId").val();
	// 职位
	var name = $("input[name='posName']");
	var flag;
	$.each(name, function(index) {
		posName = $("#" + $(name[index]).attr("id")).val();
		if (posName == null || posName == "") {
			_alert("请输入职位信息");
			flag = "1"
		}
	})
	if (flag == "1") {
		return;
	}
	// 主管
	var chargeName = $("select[name='isChargePos']");
	if (chargeName.length < 1) {
		_alert("请新增至少一条职位后保存")
		return;
	}
	var chargeNum = 0;
	var f;
	$.each(chargeName, function(index) {
		cName = $("#" + $(chargeName[index]).attr("id")).val();
		if (cName == 1) {
			chargeNum += 1;
		}
		if (chargeNum > 1) {
			_alert("每个部门只能存在一个主管")
			f = "1";
		}
	});
	if (f == "1") {
		return;
	}
	$.submit($('#frmU'), {
		dataType : 'json',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data, textStatus) {
			var messageCode = data.messageCode;
			if (message_success_code == messageCode) {
				var url = '/IMS/depart/showList.ht';
				url = url + "?companyId=" + pcid + "&cid=" + cid;
				$.go(url, {
					dataType : 'html',
					error : function() {
						hideProccessBar();
					},
					success : function(data, textStatus) {
						replaceDocument(url, data);
					}
				});
			} else {
				_alert("操作失败");
				hideProccessBar();
			}
		}
	});
}

function insertDepAndPos() {
	var pcid = $("#ht_companyId").val();
	var cid = $("#ht_communityId").val();
	if ($("#depName").val() == '' || $("#depName").val() == null) {
		_alert("请输入部门名称")
		return;
	}
	var addPosName = $("input[name='addPosName']").attr("id");
	var name = $("input[name='addPosName']");
	var chargeName = $("select[name='addPosCharge']");
	var posName;
	var flag;
	$.each(name, function(index) {
		posName = $("#" + $(name[index]).attr("id")).val();
		if (posName == null || posName == "") {
			_alert("请输入职位信息");
			flag = "1"
		}
	})
	if (flag == "1") {
		return;
	}
	var chargeNum = 0;
	var f;
	$.each(chargeName, function(index) {
		cName = $("#" + $(chargeName[index]).attr("id")).val();
		if (cName == 1) {
			chargeNum += 1;
		}
		if (chargeNum > 1) {
			_alert("每个部门只能存在一个主管")
			f = "1";
		}
	});
	if (f == "1") {
		return;
	}
	$.submit($('#frmI'), {
		dataType : 'json',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data, textStatus) {
			var messageCode = data.messageCode;
			if (message_success_code == messageCode) {
				var url = '/IMS/depart/showList.ht';
				url = url + "?companyId=" + pcid + "&cid=" + cid;
				$.go(url, {
					dataType : 'html',
					error : function() {
						hideProccessBar();
					},
					success : function(data, textStatus) {
						replaceDocument(url, data);
					}
				});
			} else {
				_alert("操作失败");
				hideProccessBar();
			}
		}
	});
}

function search() {
	var cid = $("#communityId").val();
	var companyId = $("#companyId").val();
	if (companyId == "" || companyId == null) {
		companyId = $("#ht_companyId").val();
	}
	var url = '/IMS/depart/showList.ht';
	url = url + "?cid=" + cid + "&companyId=" + companyId;
	$.go(url, {
		dataType : 'html',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data, textStatus) {
			replaceDocument(url, data);
		}
	});
}

function initialize() {
	if (communityName == null || communityName == "") {
		$("#select2-communityId-container").html("请选择小区");
	}
}

$(function() {
	if (communityName != null && communityName != "") {
		$(".box-name").html(communityName);
	} else {
		if (companyName != null && companyName != "") {
			$(".box-name").html(companyName);
		}
	}

	$("#companyId").select2({
		language : "zh-CN",
		ajax : {
			url : '/IMS/select/getCompanyList.ht',
			dataType : 'json',
			delay : 250,
			data : function(param) {
				return {
					search : param.term,// 输入的内容，会发给服务器进行查找
					// 以下两行可以在数据量大的时候用到（当下拉框往下拉的时候会加载下一页），数据量不大的时候，可以直接注释
					page : param.page || 1, // 当前页
				};
			},
			processResults : function(data, param) {
				param.page = data.pageNum;
				return {
					results : data.list,
					pagination : {
						more : data.hasNextPage
					}
				};
			}
		},
		escapeMarkup : function(markup) {
			return markup;
		},
		// minimumInputLength: 1,
		templateResult : formatRepo, // 显示查询结果
		templateSelection : function(obj) {
			$("#select2-companyId-container").html(obj.name || obj.text);
			return obj.name || obj.text;
		} // 显示选中的对象
	});

	if (companyName) {
		$("#select2-companyId-container").attr("title", companyName);
		$("#select2-companyId-container").html(companyName);
	}

	$("#communityId").select2({
		language : "zh-CN",
		ajax : {
			url : '/IMS/select/getCommunityList.ht',
			dataType : 'json',
			delay : 250,
			data : function(param) {
				return {
					search : param.term,// 输入的内容，会发给服务器进行查找
					// 以下两行可以在数据量大的时候用到（当下拉框往下拉的时候会加载下一页），数据量不大的时候，可以直接注释
					page : param.page || 1, // 当前页
					showAllItem : true,
					pcid : function() {

						var companyId = $("#companyId").val();
						if (companyId == "" || companyId == null) {
							companyId = $("#ht_companyId").val();
						}

						return companyId;
					}
				};
			},
			processResults : function(data, param) {
				param.page = data.pageNum;
				return {
					results : data.list,
					pagination : {
						more : data.hasNextPage
					}
				};
			}
		},
		escapeMarkup : function(markup) {
			return markup;
		},
		// minimumInputLength: 1,
		templateResult : formatRepo, // 显示查询结果
		templateSelection : function(obj) {
			$("#select2-communityId-container").html(obj.name || obj.text);
			return obj.name || obj.text;
		} // 显示选中的对象
	});

	if (communityName) {
		$("#select2-communityId-container").attr("title", communityName);
		$("#select2-communityId-container").html(communityName);
	} else {
		$("#select2-communityId-container").html("查看全部");
	}
	var cid = $("#ht_communityId").val();
	var pcCode = $("#ht_companyId").val();
	if ((pcCode != null || cid != null) && (pcCode != '' || cid != '') && (pcCode != 'undefined' || cid != 'undefined')) {
		$("#addDepart").show();
	} else {
		$("#addDepart").hide();
	}
});

function depList() {
	$.ajax({
		type : 'post',
		async : false,
		data : {
			cid : $("#ht_communityId").val(),
			pcid : $("#ht_companyId").val()
		},
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		url : '/IMS/select/getDepList.ht',
		dataType : 'json',
		success : function(value) {
			hideProccessBar();
			var data = value.list;// 部门
			$("#depCode").children().remove();
			if (data && data.length > 0) {
				var dom = "";
				$.each(data, function(index) {
					dom += "<option value='" + this.depCode + "'>" + this.depName + "</option>";
				});
				$("#depCode").append(dom);
				$("#depCode").select2({
					placeholder : "请选择部门"
				});
			} else {
				$("#depCode").select2({
					placeholder : "无部门记录，请先录入",
					enable : false
				});
			}
		}
	});
}

function addPos() {
	var picIndex = 1;
	var picTpl = $.format($("#copyTable").val());
	var index = picIndex;
	$('#copyBefore').before(picTpl(picIndex++));
}

function addPosU() {
	var picIndexU = 1;
	var picTplU = $.format($("#copyTableU").val());
	var index = picIndexU;
	$('#copyBeforeU').before(picTplU(picIndexU++));
}

function returnSuperior() {
	var url = "/IMS/estate/view.ht?checkUserId=" + pcid;
	$.go(url, {
		dataType : 'html',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data, textStatus) {
			replaceDocument(url, data);
		}
	});
}